package teamdamn.view;

import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JScrollPane;
import javax.swing.border.EtchedBorder;
import javax.swing.border.LineBorder;

import java.awt.Color;

import javax.swing.JTable;
import javax.swing.JLabel;

import java.awt.Font;

import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.SwingConstants;
import javax.swing.JButton;

import teamdamn.controller.DBIO;
import teamdamn.model.RFPList;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URISyntaxException;
import java.util.Date;

import javax.swing.ScrollPaneConstants;

/**
 * This panel is for the RFP Functionality.
 * @author kjudoy
 */
@SuppressWarnings("serial")
public class RFPPanel extends JPanel {
	
	private JTable tableRFP;
	
	//private GUI myGUI;
	private AnalystPanel myAnalystPanel;

	private File fileRFPStatusCsv;
	
	/**
	 * Default Constructor of RFP Panel
	 */
	public RFPPanel(AnalystPanel aAnalystPanel) {
		myAnalystPanel = aAnalystPanel;
		//myGUI = aGUI;
		
		buildRFPPanel() ;		
	}
	
	/**
	 * Creates the List of RFP text to display
	 * @author loren
	 * @author kjudoy (the csv reader for the RFP Status Information)
	 * @param theFiles RFPList.getInstance().getRFPList()
	 * @return the text to display in Object[][]
	 */
	public Object[][] getRFPtext(File[] theFiles) {
		
		File myPath = new File("repository");
		String csvFile = myPath.getAbsolutePath() + DBIO.PathSeparator() + "RFPStatus.csv";
		fileRFPStatusCsv = new File(csvFile);
		
		Object[][] RFPtext = new Object[theFiles.length][5];
		for (int i = 0; i < theFiles.length; i++) {
			RFPtext[i][0] = theFiles[i].getName();
			RFPtext[i][4] = new java.util.Date(theFiles[i].lastModified()*1000);	
			
			BufferedReader reader = null;
			try {
				reader = new BufferedReader(new FileReader(fileRFPStatusCsv));
			} catch (FileNotFoundException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			String line = "";
			
			if (reader != null) {
				try {
					while ((line = reader.readLine()) != null) {
						String[] status = line.split(", "); 
						if (status[0].equals(RFPtext[i][0])) {							
							RFPtext[i][1] = status[1];
							RFPtext[i][2] = status[2];
							RFPtext[i][3] = status[3];
							break;
						}
					}
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
				} 
			}
		}
		return RFPtext;
	}
	
	/**
	 * This method build the GUI of this panel
	 * @author kjudoy
	 * @author l2m (edited to hook into RFPList)
	 */
	public void buildRFPPanel() {
		setBorder(new LineBorder(new Color(0, 0, 0), 4));
		
		// STILL TRYING TO FIGURE OUT HOW TO WORK WITH JTABLES USING LISTS
		String[] columnNames = {"RFP Name",
				"Status",
                "Date Assigned",
                "Date Due",
                "Last Modified"
                };
		Object[][] rfpData = getRFPtext(RFPList.getInstance().getRFPList());
		
		tableRFP = new JTable(rfpData, columnNames);
		tableRFP.getColumnModel().getColumn(4).setMinWidth(180);
		tableRFP.getColumnModel().getColumn(4).setMaxWidth(180);
		tableRFP.getColumnModel().getColumn(3).setMinWidth(100);
		tableRFP.getColumnModel().getColumn(3).setMaxWidth(100);
		tableRFP.getColumnModel().getColumn(2).setMinWidth(100);
		tableRFP.getColumnModel().getColumn(2).setMaxWidth(100);
		tableRFP.getColumnModel().getColumn(1).setMinWidth(100);
		tableRFP.getColumnModel().getColumn(1).setMaxWidth(100);
		tableRFP.getColumnModel().getColumn(0).setMinWidth(180);
		tableRFP.getColumnModel().getColumn(0).setMaxWidth(180);
		
		tableRFP.setAutoResizeMode( JTable.AUTO_RESIZE_OFF );
		JScrollPane scrollPane = new JScrollPane(tableRFP);
		tableRFP.setFillsViewportHeight(true); 

		
		JLabel lblRfpTitle = new JLabel("RFP LIST");
		lblRfpTitle.setHorizontalAlignment(SwingConstants.CENTER);
		lblRfpTitle.setForeground(Color.GREEN);
		lblRfpTitle.setFont(new Font("Tahoma", Font.BOLD, 24));
		
		JButton btnRfpRefresh = new JButton("Refresh RFP");

		JButton btnRFPLaunch = new JButton("Launch RFP");
		
		
		
		// BUTTON ACTION
		btnRFPLaunch.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {		
				
				//File[] myFiles = RFPList.getInstance().getRFPList();
				if (tableRFP.getSelectedRow() >= 0) {
					//myAnalystPanel.panelToSearch();
					RFPList.getInstance().launchRFP(RFPList.getInstance().getRFPList()[tableRFP.getSelectedRow()]);
				}
			}
		});
		
		JButton btnSave = new JButton("Save Changes");
		btnSave.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				FileWriter writer = null;
				try {
					writer = new FileWriter(fileRFPStatusCsv);
					
					for(int i = 0; i < tableRFP.getRowCount(); i++) {
						for(int j=0; j < tableRFP.getColumnCount(); j++) {
							String str = "" + tableRFP.getValueAt(i, j);
							writer.append(str + ", ");
						}
						writer.append('\n');
					}
					
				    writer.flush();
				    writer.close();
					
				} catch (IOException e) {

					e.printStackTrace();
				}
				
				JFrame frame = new JFrame("MSG Save");
				JOptionPane.showMessageDialog(frame,
						"RFP Information Saved",
				        "Save Notification",
				        JOptionPane.INFORMATION_MESSAGE);

			}
		});
		// BUTTON ACTION		
//		btnToSearch.addMouseListener(new MouseAdapter() {
//			@Override
//			public void mouseClicked(MouseEvent e) {				
//				//myGUI.rfpToSearch();
//				myAnalystPanel.panelToSearch();
//			}
//		});
		
		// THIS IS thE GROUP LAYOUT FOR THE RFP PANEL
		GroupLayout groupLayout = new GroupLayout(this);
		groupLayout.setHorizontalGroup(
			groupLayout.createParallelGroup(Alignment.TRAILING)
				.addGroup(groupLayout.createSequentialGroup()
					.addContainerGap()
					.addGroup(groupLayout.createParallelGroup(Alignment.TRAILING)
						.addComponent(scrollPane, GroupLayout.DEFAULT_SIZE, 572, Short.MAX_VALUE)
						.addComponent(lblRfpTitle, GroupLayout.DEFAULT_SIZE, 572, Short.MAX_VALUE)
						.addGroup(groupLayout.createSequentialGroup()
							.addComponent(btnSave, GroupLayout.PREFERRED_SIZE, 112, GroupLayout.PREFERRED_SIZE)
							.addPreferredGap(ComponentPlacement.RELATED, 230, Short.MAX_VALUE)
							.addComponent(btnRFPLaunch, GroupLayout.PREFERRED_SIZE, 112, GroupLayout.PREFERRED_SIZE)
							.addPreferredGap(ComponentPlacement.RELATED)
							.addComponent(btnRfpRefresh, GroupLayout.PREFERRED_SIZE, 112, GroupLayout.PREFERRED_SIZE)))
					.addContainerGap())
		);
		groupLayout.setVerticalGroup(
			groupLayout.createParallelGroup(Alignment.LEADING)
				.addGroup(groupLayout.createSequentialGroup()
					.addGap(27)
					.addComponent(lblRfpTitle, GroupLayout.PREFERRED_SIZE, 29, GroupLayout.PREFERRED_SIZE)
					.addPreferredGap(ComponentPlacement.RELATED)
					.addComponent(scrollPane, GroupLayout.DEFAULT_SIZE, 263, Short.MAX_VALUE)
					.addPreferredGap(ComponentPlacement.RELATED)
					.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
						.addComponent(btnRfpRefresh)
						.addComponent(btnRFPLaunch)
						.addComponent(btnSave))
					.addContainerGap())
		);
		setLayout(groupLayout);
	}
}
